import json
from test_api import getdir
from view import login
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
import pyodbc
from utils.treeDemo import handle_exceptions
from control.SystemSet import SystemSet
from control.HomePage import HomePage

class Login(login.Ui_MainWindow, QMainWindow):
    def __init__(self):
        super(Login, self).__init__()
        self.setupUi(self)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.pushButton_2.clicked.connect(self.close_button)  # 连接关闭窗口按钮
        self.pushButton_5.clicked.connect(self.database_set)  # 配置数据库连接
        self.pushButton_6.clicked.connect(self.login_homepage)  # 进入首页
        self.connect_to_database()

    def login_homepage(self):
        self.next_home = HomePage()
        self.next_home.show()
        self.close()

    def database_set(self):
        self.next_page = SystemSet()
        self.next_page.show()

    def close_button(self):
        self.close()

    @handle_exceptions
    def connect_to_database(self):
        # 读取设置文件
        self.settings_file = getdir() + 'api/ConfigJson.txt'
        with open(self.settings_file, 'r', encoding='utf-8') as file:
            settings = json.load(file)
        try:
            # 构建连接字符串
            connection_string = (
                r'DRIVER={{ODBC Driver 17 for SQL Server}};'
                r'SERVER={dataIp};'  # 使用 settings['dataIp']
                r'DATABASE={database};'
                r'UID={user};'
                r'PWD={password}'
            ).format(dataIp=settings['dataIp'], database=settings['database'], user=settings['user'],
                     password=settings['password'])

            # 连接数据库
            connection = pyodbc.connect(connection_string)
            # 连接成功，关闭连接
            connection.close()
            # 弹出成功提示框
            # QMessageBox.information(None, "数据库连接成功", "成功连接到数据库。")
        except pyodbc.Error as e:
            # 连接失败，弹出失败提示框
            QMessageBox.critical(None, "数据库连接失败", str(e))
            self.pushButton_7.setText("数据库连接失败")

if __name__ == '__main__':
    app = QApplication([])
    window = Login()
    window.show()
    app.exec_()